package linker.plugin;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class MailOne extends PluginItem implements ActionListener {
	// @_@
	private static final long serialVersionUID = 1L;

	private JTextField subjectField = new JTextField(20);

	private JTextField fromField = new JTextField(20);

	private JTextField toField = new JTextField(20);

	private JButton sendButton = new JButton("Send");

	private JTextArea contentArea = new JTextArea();

	private MailAuthenticator mailAuthenticator = null;

	public MailOne() {
		super("MailOne");
		setName("MailOne");
	}

	public String toString() {
		return "MailOne";
	}

	public void create() {
		Container container = getContentPane();

		JPanel userPanel = new JPanel();
		userPanel.add(new JLabel("From"));
		userPanel.add(fromField);
		userPanel.add(new JLabel("To"));
		userPanel.add(toField);
		sendButton.addActionListener(this);
		userPanel.add(sendButton);
		container.add(userPanel, BorderLayout.SOUTH);

		JPanel subjectPanel = new JPanel();
		subjectPanel.add(new JLabel("Subject"));
		subjectPanel.add(subjectField);
		container.add(subjectPanel, BorderLayout.NORTH);

		container.add(new JScrollPane(contentArea), BorderLayout.CENTER);

		setWindow();
	}

	public void setPluginDir(String dir) {
		icon = new ImageIcon(dir + fileSeparator + "icon.png");

		create();
	}

	public static void main(String args[]) {

		MailOne mail = new MailOne();
		mail.setPluginDir("/home/cox/Desktop/linker/resources/plugins/MailOne");
		mail.setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == sendButton) {
			sendMail();
		}
	}

	private void sendMail() {
		if (mailAuthenticator == null)
			mailAuthenticator = new MailAuthenticator();

		try {
			SimpleEmail mail = new SimpleEmail();
			mail.setHostName("smtp.gmail.com");
			mail.setFrom(fromField.getText());
			mail.addTo(toField.getText());
			mail.setSubject(subjectField.getText());
			mail.setMsg(contentArea.getText());
			mail.setSSL(true);
			mail.setAuthenticator(mailAuthenticator);
			mail.send();

			JOptionPane.showMessageDialog(this, "Mail sent");
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}

}
